import {ChangeDetectorRef, Component, NgZone, ViewChild} from '@angular/core';
import {
    IonicPage,
    NavController,
    NavParams,
    ToastController,
    ActionSheetController,
    Platform, Select
} from 'ionic-angular';
import * as moment from 'moment';

import {Keyboard} from "ionic-angular"
import {MessageBushService} from "../../../services/common/message-bush.service";
import {AlertController} from 'ionic-angular';
import {Content} from 'ionic-angular';
import {LoadingService} from "../../../services/common/loading.service";
import {StaffMod} from "../../../model/pages/add-staff/addNewStaff/addNewStaff.model";
import {AddNewStaffProvider} from "../../../providers/add-staff/add-new-staff/add-new-staff.provider";
import {AdpActionSheetController} from "../../../components/common/adp-action-sheet/adp-action-sheet-controller";
import $ from 'jquery';

@IonicPage()
@Component({
    selector: 'page-add-new-staff',
    templateUrl: 'add-new-staff.html',
    providers: [
        AddNewStaffProvider,
        LoadingService
    ]
})
export class AddNewStaffPage {


    //表单验证提示信息
    public FormTip = {
        name: "请填写增员对象姓名",
        phone: "请填写正确的电话",
        phoneNumber: '请填写电话号码',
        postCode: "请填写正确的邮编",
        otherIns: "请选择保险类型",
        income: "请输入正确的工资",
        addressTip: "地址不能为空"
    };

    @ViewChild(Content) content: Content;
    @ViewChild("select") select: Select;
    @ViewChild("select1") select1: Select;
    @ViewChild("select2") select2: Select;
    // picker当前最大时间节点
    private maxDate: string = moment(new Date()).format('YYYY-MM-DD');

    // 客户界面model总信息
    private staffModel: StaffMod = new StaffMod();

    // 传参 model 信息
    private staffParamsModel: StaffMod = new StaffMod();
    //日期选择器配置
    private pickerOptions = {
        cssClass: 'client-add-picker'
    };
    // input ReadOnly
    public readonly = true;
    // 展开更多
    public isOpen: boolean = false;
    public testPhone: RegExp = /^[0-9]*$/;
    public testName: RegExp = /^[a-zA-Z\u4e00-\u9fa5\·\ \s]{1,20}$/;
    public isDisabled = false;
    public jobKind = [
        {"name": "10万以下", "value": '1'},
        {"name": "10万 - 20万", "value": '2'},
        {"name": "20万 - 30万", "value": '3'},
        {"name": "30万 - 50万", "value": '4'},
        {"name": "50万 - 100万", "value": '5'},
        {"name": "100万以上", "value": '6'},
    ];
    public staffData;
    public clientHeight;
    public staffDataNew;


    constructor(public navCtrl: NavController,
                public navParams: NavParams,
                public toastCtrl: ToastController,
                private ref: ChangeDetectorRef,
                public staffAddPro: AddNewStaffProvider,
                public keyboard: Keyboard,
                public alert: AlertController,
                public actionSheetCtrl: ActionSheetController,
                public platform: Platform,
                public zone: NgZone,
                public load: LoadingService,
                public adpActionSheet: AdpActionSheetController) {
        this.clientHeight = document.body.clientHeight;
    }


    ionViewDidLoad() {
        this.editStaffData();
        this.showSex();
        this.scrollHeight = $('.scroll-content')[$('.scroll-content').length - 1].scrollTop;
    }

    ionViewDidEnter() {
    }

    ionViewWillLeave() {
        this.select.close();
        this.select1.close();
        this.select2.close();
    }

    height;
    contentHeight;
    public scrollHeight = 0;

    /**
     *  滚动失光标
     */
    onScroll() {
        this.scrollHeight = $('.scroll-content')[$('.scroll-content').length - 1].scrollTop;
    }

    /**
     * input获得焦点
     * @param ele
     * @param ev
     */
    inputFocus(ev) {

        ev.stopPropagation();
        ev.preventDefault();
        // 当前屏幕高度..
        this.contentHeight = document.body.clientHeight;

        if ($(ev.target).offset().top > this.contentHeight / 2) {
            this.content.scrollTo(0, $(ev.target.offsetParent).offset().top +
                this.scrollHeight - 200, 500);
        }
        console.log($(ev.target).offset().top)
    }

    /**
     *  初始化界面。新增，编辑
     */
    editStaffData() {
        this.staffData = this.navParams.get("data");
        let addData = this.navParams.get('addData');
        if (this.staffData) {
            this.staffModel = JSON.parse(JSON.stringify(this.navParams.get('data')));
            if (!this.staffModel.mobileList || this.staffModel.mobileList.length == 0) {
                this.staffModel.mobileList = [{mobile: '', id: "", isDel: false}];
            }
            if (!this.staffModel.income) {
                // this.staffModel.income = Number(this.staffModel.income).toFixed();
                this.staffModel.income = '请选择';

            }
        } else {
            if (addData) {
                this.staffModel.name = addData.name;
                this.staffModel.mobileList = [{mobile: addData.tel, id: "", isDel: false}];

            } else {
                this.staffModel.mobileList = [{mobile: '', id: "", isDel: false}];
            }
        }
    }

    /**
     * 输入工作年限禁止输入非数字字符
     */
    inputOnchangeJob(ev) {
        let val = ev.value.replace(/[^0-9]/ig, '');
        if (ev.value.length > 1) {
            //当大于1位数的时候，去掉第一个0
            val = val.replace(/^[0]+/, '');
        }
        ev.value = val;
        this.staffModel.workingYears = val;

    }

    private maxDateYear = Number(moment(new Date()).format('YYYY'));

    /**
     * 向datatpicker添加年度顺序排列数据：[2010,2011,2012...2100]
     */
    getYearList(start: number, end: number = this.maxDateYear) {

        let years = [];
        if (typeof start == 'number' && typeof end == 'number' && start && end) {
            for (let y = start; y <= end; y++) {
                years.push(y)
            }
        } else {
            for (let y = start; y <= end; y++) {
                years.push(y)
            }
        }
        return years
    }

    /**
     * 性别选择
     */
    chooseSex() {
        this.adpActionSheet.create({
            title: '性别',
            buttons: [
                {
                    text: '男',
                    role: 'destructive',
                    cssClass: this.staffModel.sex == "男" ? 'action-sheet-selected' : '',
                    handler: () => {
                        this.staffModel.sex = "男";
                    }
                }, {
                    text: '女',
                    cssClass: this.staffModel.sex == "女" ? 'action-sheet-selected' : '',
                    handler: () => {
                        this.staffModel.sex = "女";
                    }
                }, {
                    text: '取消',
                    role: 'cancel',
                    handler: () => {
                        console.log('Cancel clicked');
                    }
                }
            ]
        }).present();
    }

    /**
     * 打开选择年收入
     */

    chooseSalary() {
        let jobArray = [];
        // for (let m in this.jobKind) {
        //
        // }
        this.jobKind.forEach((m) => {
            let obj = {};
            obj['text'] = m.name;
            obj['cssClass'] = this.staffModel.income == m.name ? 'action-sheet-selected' : '';
            obj['handler'] = () => {
                this.staffModel.income = m.name;
            };
            jobArray.push(obj);
        });
        this.adpActionSheet.create({
            title: '年收入',
            buttons: jobArray,
            cssClass: 'mySelect'
        }).present();
    }

    /**
     * 初始化页面显示性别
     */
    showSex() {
        if (this.staffModel.sex && this.staffModel.sex == 'M') {
            this.staffModel.sex = "男";
        }
        if (this.staffModel.sex && this.staffModel.sex == 'F') {
            this.staffModel.sex = "女";
        }
        if (!this.staffModel.sex) {
            this.staffModel.sex = "请选择";
        }
        if (!this.staffModel.income) {
            this.staffModel.income = '请选择';
        }
    }

    /**
     * 添加新手机
     */
    addNewPhone(ev) {
        ev.preventDefault();
        ev.stopPropagation();
        this.staffModel.mobileList.push({mobile: '', id: "", isDel: false});
        this.ref.detectChanges();
    }

    /**
     * 输入电话号码
     */
    inputOnchangeTel(i, ev) {
        let val = ev.value.replace(/[^0-9]/ig, '');
        ev.value = val;
        this.staffModel.mobileList[i].mobile = val;
    }

    /**
     * 删除界面手机
     */
    delLocalPhone(ind, ev, data, isEmpty) {
        ev.preventDefault();
        ev.stopPropagation();
        if (isEmpty) {
            data.mobileList.splice(ind, 1);
        } else {
            this.staffModel.mobileList.splice(ind, 1);
        }
        this.ref.detectChanges();
    }


    /**
     * 页面表单验证\提示
     */
    getCheckData(data) {
        const testPhone: RegExp = /^[0-9\-]*$/;
        const incomePatrn: RegExp = /^[0-9.]*$/;
        let phoneTip: boolean = true;
        let phoneNumberTip: boolean = false;
        let mobileList2 = [];
        for (let i = 0; i < data.mobileList.length; i++) {
            // push有号码的电话
            if (data.mobileList[i].mobile) {
                mobileList2.push(data.mobileList[i]);
            }
        }
        data.mobileList = mobileList2;
        data.name = data.name && data.name.trim();
        if (data.mobileList && data.mobileList.length) {
            for (let i = 0; i < data.mobileList.length; i++) {
                if (testPhone.test(data.mobileList[i].mobile) == false &&
                    data.mobileList[i].defaultIndicator !== 0) {
                    phoneTip = false;
                }
            }
        }
        if (!data.mobileList.length || data.mobileList[0].mobile == '') {
            phoneNumberTip = true;
        }
        if (!data.name) {
            this.toast(this.FormTip.name, "bottom");
            return false;
        } else if (!this.testName.test(data.name) && !data.virtualTime) {
            this.toast("姓名仅支持汉字或英文字母", "bottom");
            return false;
        } else if (phoneTip == false) {
            this.toast(this.FormTip.phone, "middle");
            return false;
        } else if (phoneNumberTip) {
            this.toast(this.FormTip.phoneNumber, "middle");
            return false;
        } else {
            return true;
        }
    }

    /**
     * 处理参数
     */
    checkParamsModel(checkPhone = undefined) {

        let c = this.staffParamsModel;
        if (checkPhone) {
            c.checkMobile = false;
        } else {
            c.checkMobile = true;
        }


        if (this.staffData) {
            c.recruitId = this.staffData.recruitId;
            c.recruitTargetId = this.staffData.recruitTargetId;
        }
        if (c.sex == "请选择") {
            c.sex = '';
        } else if (c.sex == "男") {
            c.sex = "M"
        } else if (c.sex == "女") {
            c.sex = "F";
        }
        if (!this.staffData) {
            c.source = "手工添加";
        }
        if (c.income == '请选择') {
            c.income = ''
        }
        return c;
    }

    getData() {
        let pageParams = this.navParams.get('pageParams');
        this.load.showLoading();
        this.staffAddPro.addNewStaff(this.checkParamsModel()).subscribe(res => {
            this.load.dismissLoading();
            this.toast("保存成功", "bottom");
            MessageBushService.setMessage(MessageBushService.keys.addStuffSaveSuccess, '1');
            MessageBushService.setMessage(MessageBushService.keys.teamTeamIncreaseUpdate, '1');
            this.isDisabled = false;
            if (this.staffData) {
                this.backToProPage(1);

            } else {
                if (pageParams == 'pool') {
                    this.backToProPage(1);
                } else {
                    this.navCtrl.push('TalentPoolPage', {'pageParams': "pool"});
                }
            }


        }, (error) => {
            this.isDisabled = false;
            this.load.dismissLoading();
            if (JSON.parse(error.error).status == 999) {
                if (JSON.parse(error.error).exception == "Prospect already exist") {
                    this.toast("增员对象已存在", "bottom");
                } else if (JSON.parse(error.error).exception == "Mobile already exist") {
                    this.alert.create({
                        title: '电话已经存在',
                        message: '当前电话已存在，是否继续添加为增员对象？',
                        cssClass:'ifAddCustStaff',
                        buttons: [{
                            text: '取消', handler: () => {

                            }
                        }, {
                            text: '确定', handler: () => {
                                this.load.showLoading();
                                this.isDisabled = true;
                                this.staffAddPro.addNewStaff(this.checkParamsModel(1)).subscribe(res => {
                                    this.isDisabled = false;
                                    MessageBushService.setMessage(MessageBushService.keys.addStuffSaveSuccess, '1');
                                    MessageBushService.setMessage(MessageBushService.keys.teamTeamIncreaseUpdate, '1');
                                    this.load.dismissLoading();
                                    if (this.staffData) {
                                        this.backToProPage(1);
                                    } else {
                                        if (pageParams == 'pool') {
                                            this.backToProPage(1);
                                        } else {
                                            this.navCtrl.push('TalentPoolPage', {'pageParams': "pool"});
                                        }
                                    }

                                }, error => {
                                    this.load.dismissLoading();
                                    this.isDisabled = false;
                                })
                            }
                        }]
                    }).present();
                }
            }else{
                this.toast("网络错误，请重试！", "middle");
            }
        });
    }

    /**
     * 新建增员对象
     */
    addStaffCust(ev) {
        this.isDisabled = true;
        this.staffParamsModel = JSON.parse(JSON.stringify(this.staffModel));
        if (!this.getCheckData(this.staffParamsModel)) {
            this.isDisabled = false;
            return;
        }

        // setTimeout(()=>{
        this.getData();
        // },100);
        //this.isDisabled = false;
    }

    /**
     *  toast 提示信息
     * @param {string} message 提示内容
     * @param {string} position 显示位置
     */
    toast(message: string, position: string) {
        this.toastCtrl.create({
            message: message,
            position: 'middle',
            duration: 1500
        }).present();
    }

    /**
     *  返回
     */
    backToProPage(isSave) {
        if (!isSave) {
            MessageBushService.setMessage(MessageBushService.keys.addStuffSaveSuccess, '');
        }
        this.navCtrl.pop(null);
    }

}
